package com.unnet.yjs.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.DecimalFormat;
/**
 * Email: love1208tt@foxmail.com
 * Copyright (c)  2019. missbe
 * @author lyg   19-7-10 下午7:48
 *
 *
 **/
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 转换文件大小格式
     * @param fileByte 文件字节
     * @return ？B K M G
     */
    public static String formatFileSize(long fileByte) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeFormat = "";
        if (fileByte < 1024) {
            fileSizeFormat = df.format((double) fileByte) + "B";
        } else if (fileByte < 1048576) {
            fileSizeFormat = df.format((double) fileByte / 1024) + "K";
        } else if (fileByte < 1073741824) {
            fileSizeFormat = df.format((double) fileByte / 1048576) + "M";
        } else {
            fileSizeFormat = df.format((double) fileByte / 1073741824) + "G";
        }
        return fileSizeFormat;
    }

    /**
     * 递归计算文件夹或文件占用大小
     * @param file 文件
     * @return 文件总大小
     */
    public static long getFileOrFolderSize(File file){
        if (file.isFile()) {
            return file.length();
        }
        long totalSize = 0;
        File[] listFiles = file.listFiles();
        assert listFiles != null;
        for (File f : listFiles) {
            if (f.isDirectory()) {
                totalSize += getFileOrFolderSize(f);
            }else{
                totalSize += f.length();
            }
        }///end for
        return totalSize;
    }

    /**
     * 清除指定目录下面的空文件
     * @param dir 指定目录
     */
    public static void deleteEmptyFile(File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            assert files != null;
            for (File file : files) {
                if (file.isFile() && file.length() == 0) {
                    boolean suc = file.delete();
                    if (suc) {
                        LOGGER.info(file.getName() + " delete success.");
                    }else{
                        LOGGER.info(file.getName() + " delete fail.");
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        File file = new File("E:\\data\\oneclick\\oss\\Java面试知识点整理手册.pdf");
        boolean suc = file.delete();
        System.out.println(suc);
    }
}
